//
//  CustomLayout.m
//  CollectionView自定义layout练习
//
//  Created by dllo on 16/9/1.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "CustomLayout.h"
@interface CustomLayout ()
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *attributesArray;
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, assign) CGFloat contentWidth;
@end
@implementation CustomLayout
- (instancetype)init {
    self = [super init];
    if (self) {
        _attributesArray = [NSMutableArray array];
        _numberOfColumns = 2;
        _contentWidth = self.collectionView.bounds.size.width * 2;
        _cellMargin = 10.0f;
       
    }
    return self;
}
//- (CGFloat)itemWidth {
//    CGFloat allMarginWidth = (_numberOfColumns + 1) *_cellMargin;
//    CGFloat noMarginWidth = CGRectGetWidth(self.collectionView.bounds) - allMarginWidth;
//    return noMarginWidth / _numberOfColumns;
//}
- (void)prepareLayout {
    // 定义当前在第几列
//    NSInteger column = 0;
//    // 定义当前在第几行
//    NSInteger line = 0;
    // 遍历0区的所有item
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        CGFloat x = 0.0;
        CGFloat y = 0.0;
        CGFloat width = (self.collectionView.frame.size.width - 50) / 4.0;
        CGFloat height = (self.collectionView.frame.size.height - _cellMargin * 3) / 2.0;
        if (i >= 0 && i < 4) {
            x = _cellMargin * (i + 1) + width * i;
            y = _cellMargin;
        } else if (i >= 4 && i < 8) {
            x = _cellMargin * (i + 1 - 4) + width * (i - 4);
            y = _cellMargin  + height;
        } else {
            x = self.collectionView.bounds.size.width + _cellMargin * (i + 1 - 8) + width * (i - 8);
            y = _cellMargin;
        }
        
        layoutAttributes.frame = CGRectMake(x, y, width, height);
        [self.attributesArray addObject:layoutAttributes];
    }
    self.contentWidth = self.collectionView.frame.size.width * 2;
    
}
#pragma mark - 返回的是每个item对应的布局属性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
//    NSLog(@"%@", _attributesArray);
    return _attributesArray;
}
#pragma mark - 负责collectionView的滚动范围
- (CGSize)collectionViewContentSize {
    return CGSizeMake(_contentWidth, 0);
}

@end
